<template>
  <div class="scam-detail-page">
    <div class="section-content">
      <div v-if="loading" class="loading-section">
        <el-skeleton :rows="3" animated />
      </div>
      <div v-else-if="!scam" class="empty-state">
        <el-empty description="信息不存在" />
      </div>
      <div v-else class="scam-detail">
        <div class="scam-header">
          <h1>{{ scam.title }}</h1>
          <el-tag :type="getStatusType(scam.status)" size="large">
            {{ getStatusText(scam.status) }}
          </el-tag>
        </div>

        <div class="scam-info">
          <div class="info-item">
            <el-icon><Phone /></el-icon>
            <span class="label">举报号码：</span>
            <span class="value">{{ scam.phoneNumber || scam.phone }}</span>
          </div>
          
          <div class="info-item">
            <el-icon><User /></el-icon>
            <span class="label">举报人：</span>
            <span class="value">{{ scam.author?.username || '匿名' }}</span>
          </div>
          
          <div class="info-item">
            <el-icon><Calendar /></el-icon>
            <span class="label">举报时间：</span>
            <span class="value">{{ formatDate(scam.createdAt) }}</span>
          </div>

          <div class="info-item">
            <el-icon><View /></el-icon>
            <span class="label">浏览次数：</span>
            <span class="value">{{ scam.views || 0 }}</span>
          </div>
        </div>

        <div class="scam-content">
          <h2>详细描述</h2>
          <p>{{ scam.description }}</p>
        </div>

        <div v-if="scam.evidence && scam.evidence.length > 0" class="evidence-section">
          <h2>证据材料</h2>
          <div class="evidence-grid">
            <div v-for="(evidence, index) in scam.evidence" :key="index" class="evidence-item">
              <el-image 
                :src="evidence"
                fit="cover"
                :preview-src-list="scam.evidence"
                :initial-index="index"
              />
            </div>
          </div>
        </div>

        <div class="comments-section">
          <h2>评论区 ({{ commentsList.length }})</h2>
          
          <div v-if="userStore.token" class="comment-form">
            <el-input
              v-model="newComment"
              type="textarea"
              :rows="3"
              placeholder="写下你的评论..."
              :maxlength="500"
              show-word-limit
            />
            <el-button 
              type="primary" 
              @click="handleComment"
              :loading="commenting"
              :disabled="!newComment.trim()"
            >
              发表评论
            </el-button>
          </div>
          <div v-else class="login-tip">
            <router-link to="/login" class="login-link">登录</router-link>
            后参与评论
          </div>

          <div class="comments-list">
            <div v-if="commentsList.length === 0" class="empty-state">
              <el-empty description="暂无评论" />
            </div>
            <div v-else>
              <div v-for="comment in commentsList" :key="comment.id" class="comment-item">
                <div class="comment-header">
                  <div class="comment-author">
                    <span class="author-name">{{ comment.author?.username || '匿名' }}</span>
                    <span class="comment-time">{{ formatDate(comment.createdAt) }}</span>
                  </div>
                  <div class="comment-actions">
                    <el-button 
                      type="primary" 
                      link
                      @click="handleReply(comment)"
                    >
                      回复
                    </el-button>
                    <el-button 
                      v-if="canDeleteComment(comment)"
                      type="danger" 
                      link
                      @click="handleDeleteComment(comment.id)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
                <p class="comment-content">{{ comment.content }}</p>

                <!-- 回复列表 -->
                <div v-if="comment.replies && comment.replies.length > 0" class="replies-list">
                  <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                    <div class="reply-header">
                      <div class="reply-author">
                        <span class="author-name">{{ reply.author?.username || '匿名' }}</span>
                        <span class="reply-time">{{ formatDate(reply.createdAt) }}</span>
                      </div>
                      <div class="reply-actions">
                        <el-button 
                          type="primary" 
                          link
                          @click="handleReply(comment, reply)"
                        >
                          回复
                        </el-button>
                        <el-button 
                          v-if="canDeleteComment(reply)"
                          type="danger" 
                          link
                          @click="handleDeleteComment(reply.id)"
                        >
                          删除
                        </el-button>
                      </div>
                    </div>
                    <p class="reply-content">{{ reply.content }}</p>
                  </div>
                </div>

                <!-- 回复表单 -->
                <div v-if="replyingTo === comment.id" class="reply-form">
                  <el-input
                    v-model="replyContent"
                    type="textarea"
                    :rows="2"
                    :placeholder="replyToUser ? `回复 ${replyToUser}：` : '写下你的回复...'"
                    :maxlength="500"
                    show-word-limit
                  />
                  <div class="reply-form-actions">
                    <el-button 
                      type="primary" 
                      @click="submitReply(comment.id)"
                      :loading="replying"
                      :disabled="!replyContent.trim()"
                    >
                      发表回复
                    </el-button>
                    <el-button @click="cancelReply">取消</el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useUserStore } from '../stores/user'
import { scams, comments } from '../api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Phone, User, Calendar, View } from '@element-plus/icons-vue'

const route = useRoute()
const userStore = useUserStore()

const scam = ref(null)
const commentsList = ref([])
const newComment = ref('')
const loading = ref(true)
const commenting = ref(false)
const replyingTo = ref(null)
const replyContent = ref('')
const replyToUser = ref('')
const replying = ref(false)

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getStatusType = (status) => {
  const types = {
    'verified': 'success',
    'pending': 'warning',
    'rejected': 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    'verified': '已验证',
    'pending': '待审核',
    'rejected': '已拒绝'
  }
  return texts[status] || '未知'
}

const fetchScamDetail = async () => {
  loading.value = true
  try {
    const response = await scams.getDetail(route.params.id)
    scam.value = response
    await fetchComments()
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const fetchComments = async () => {
  try {
    const response = await comments.getList(route.params.id)
    if (response && response.comments) {
      commentsList.value = response.comments
    } else {
      commentsList.value = []
    }
  } catch (error) {
    console.error('获取评论失败:', error)
    ElMessage.error('获取评论失败，请稍后重试')
    commentsList.value = []
  }
}

const handleComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  try {
    commenting.value = true
    await comments.create(route.params.id, {
      content: newComment.value
    })
    newComment.value = ''
    await fetchComments()
    ElMessage.success('评论成功')
  } catch (error) {
    console.error('评论失败:', error)
    ElMessage.error('评论失败，请稍后重试')
  } finally {
    commenting.value = false
  }
}

const canDeleteComment = (comment) => {
  return userStore.userRole === 'admin' || 
         (userStore.user && userStore.user.id === comment.author?.id)
}

const handleDeleteComment = async (commentId) => {
  try {
    await comments.delete(route.params.id, commentId)
    await fetchComments()
    ElMessage.success('删除成功')
  } catch (error) {
    console.error('删除评论失败:', error)
    ElMessage.error('删除失败，请稍后重试')
  }
}

const handleReply = (comment, reply = null) => {
  replyingTo.value = comment.id
  replyToUser.value = reply ? reply.author?.username : null
  replyContent.value = ''
}

const cancelReply = () => {
  replyingTo.value = null
  replyToUser.value = null
  replyContent.value = ''
}

const submitReply = async (parentId) => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }

  try {
    replying.value = true
    await comments.create(route.params.id, {
      content: replyContent.value,
      parentId
    })
    replyContent.value = ''
    replyingTo.value = null
    replyToUser.value = null
    await fetchComments()
    ElMessage.success('回复成功')
  } catch (error) {
    console.error('回复失败:', error)
    ElMessage.error('回复失败，请稍后重试')
  } finally {
    replying.value = false
  }
}

onMounted(() => {
  fetchScamDetail()
})
</script>

<style scoped>
.scam-detail-page {
  padding: 40px 0;
  background-color: #f8f9fa;
  min-height: calc(100vh - 72px);
}

.section-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.loading-section,
.empty-state,
.scam-detail {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.scam-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #edf2f7;
}

.scam-header h1 {
  margin: 0;
  font-size: 1.8rem;
  color: #2c3e50;
  font-weight: 600;
}

.scam-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-item .label {
  color: #64748b;
  font-size: 0.95rem;
}

.info-item .value {
  color: #2c3e50;
  font-weight: 500;
}

.scam-content {
  margin-bottom: 40px;
}

.scam-content h2 {
  font-size: 1.4rem;
  color: #2c3e50;
  margin-bottom: 20px;
}

.scam-content p {
  color: #4a5568;
  line-height: 1.8;
  white-space: pre-wrap;
}

.evidence-section {
  margin-bottom: 40px;
}

.evidence-section h2 {
  font-size: 1.4rem;
  color: #2c3e50;
  margin-bottom: 20px;
}

.evidence-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.evidence-item {
  aspect-ratio: 1;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #edf2f7;
}

.evidence-item :deep(.el-image) {
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.comments-section {
  margin-top: 40px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.comments-section h2 {
  font-size: 1.4rem;
  color: #2c3e50;
  margin-bottom: 20px;
}

.comment-form {
  margin-bottom: 30px;
}

.comment-form .el-button {
  margin-top: 15px;
}

.login-tip {
  text-align: center;
  padding: 20px;
  color: #64748b;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 30px;
}

.login-link {
  color: #3498db;
  text-decoration: none;
  font-weight: 500;
}

.login-link:hover {
  text-decoration: underline;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.comment-item {
  padding: 15px;
  border-bottom: 1px solid #e2e8f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.comment-author {
  display: flex;
  align-items: center;
  gap: 10px;
}

.author-name {
  font-weight: 500;
  color: #2d3748;
}

.comment-time {
  color: #64748b;
  font-size: 0.9rem;
}

.comment-content {
  color: #4a5568;
  line-height: 1.6;
  margin: 0;
  white-space: pre-wrap;
}

.replies-list {
  margin-top: 15px;
  padding-left: 20px;
  border-left: 2px solid #e2e8f0;
}

.reply-item {
  margin-top: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.reply-author {
  display: flex;
  align-items: center;
  gap: 10px;
}

.reply-time {
  color: #64748b;
  font-size: 0.9rem;
}

.reply-content {
  color: #4a5568;
  line-height: 1.6;
  margin: 0;
  white-space: pre-wrap;
}

.reply-form {
  margin-top: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.reply-form-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.comment-actions {
  display: flex;
  gap: 10px;
}

.reply-actions {
  display: flex;
  gap: 10px;
}

@media (max-width: 768px) {
  .scam-detail-page {
    padding: 20px 0;
  }

  .scam-header h1 {
    font-size: 1.5rem;
  }

  .scam-info {
    grid-template-columns: 1fr;
    gap: 15px;
  }

  .evidence-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 15px;
  }

  .comments-section {
    padding: 15px;
  }

  .comment-header,
  .reply-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .comment-actions,
  .reply-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style> 